<template>
  <Card v-show="shuax">
    <div class="flexCSB">
      <Button type="primary" @click="addAccount">添加账号</Button>
      <div style="display: flex;">
        <RadioGroup v-model="states" type="button" @on-change="change">
          <Radio label="0">全部</Radio>
          <Radio label="1">未审核</Radio>
          <Radio label="2">已通过</Radio>
          <Radio label="3">已拒绝</Radio>
        </RadioGroup>
        <Input
          placeholder="请输入手机号或博物馆名称"
          suffix="ios-search"
          style="width:300px;margin-left:10px"
          v-model="phone"
          @on-change="change"
        ></Input>
      </div>
      <!-- 这是被遗弃的 -->
      <!-- 		    <RadioGroup v-model="type" type="button" @on-change="change">
		        <Radio label="0">全部</Radio>
		        <Radio label="1">普通用户</Radio>
		        <Radio label="2">博物馆人员</Radio>
		        <Radio label="3">播音员</Radio>
      </RadioGroup>-->
    </div>

    <Table
      class="table"
      :loading="loading1"
      v-if="states==0 || states==2"
      @on-row-dblclick="onRowDblclick"
      highlight-row
      :columns="columns"
      :data="data"
    ></Table>
    <Table
      @on-row-dblclick="onRowDblclick"
      class="table"
      :loading="loading1"
      v-if="states==1 || states==3"
      highlight-row
      :columns="columns2"
      :data="data"></Table>
    <Page
      class="page"
      show-total
      :total="total"
      :current.sync="current"
      show-elevator
      @on-change="changePage"
    />

    <Modal title="修改密码" v-model="passwordModal">
      <Input placeholder="请输入新密码" v-model="pswdText"></Input>
      <div slot="footer">
        <Button type="warning" class="Button" @click="passwordModal = false">关闭</Button>
        <Button type="primary" class="Button" @click="submit" :loading="loading2">提交</Button>
      </div>
    </Modal>
    <el-button :plain="true" @click="open2" v-show="yingc">成功</el-button>
    <el-button type="text" @click="open" v-show="yingc">点击打开 Message Box</el-button>
    <Modal title="修改手机号" v-model="updatatel">
      <Input placeholder="请输入新手机号" v-model="tel"></Input>
      <div slot="footer">
        <Button type="warning" class="Button" @click="updatatel = false">关闭</Button>
        <Button type="primary" class="Button" @click="updataTelSubmit" :loading="loading2">提交</Button>
      </div>
    </Modal>

    <Modal title="修改权限" v-model="jurisdictionModal" width="650">
      <el-tree :data="treeData" :props="defaultProps" :default-expand-all="true">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <RadioGroup v-model="data.permissions" type="button" size="small" v-if="data.isEdit">
                  <Radio :label="data.p1">查看</Radio>
                  <Radio :label="data.p2">查看&编辑</Radio>
                  <Radio :label="data.p3">查看&删除</Radio>
                  <Radio :label="data.p4">全部</Radio>
                  <Radio label>无权限</Radio>
                </RadioGroup>
              </span>
            </span>
      </el-tree>
      <div slot="footer">
        <Button class="Button" type="primary" @click="submit2" :loading="loading4">确认修改</Button>
      </div>
    </Modal>

    <Modal v-model="addAccountModal" title="新增账号" width="650">
      <Form ref="form" :model="createData" :label-width="100">
         <FormItem label="姓名：" prop="realName">
          <Input v-model="createData.realName" clearable/>
        </FormItem>
        <FormItem label="账号：" prop="username">
          <Input v-model="createData.username" clearable/>
        </FormItem>
        
        <FormItem label="邮箱：" prop="email">
          <Input v-model="createData.email" clearable/>
        </FormItem>
        <!--         	<FormItem label="密码：" prop="password">
	          		<Input type="password" password v-model="createData.password"></Input>
        </FormItem>-->
        <FormItem label="手机号：" prop="phone">
          <Input v-model="createData.phone" clearable/>
        </FormItem>
        <FormItem label="身份：" prop="museumId">
          <Select filterable v-model="createData.museumId">
            <template v-for="item in museumList">
              <Option :value="item.id">{{item.name}}</Option>
            </template>
          </Select>
        </FormItem>
        <FormItem label="状态：" prop="states">
          <RadioGroup v-model="createData.states" type="button">
            <Radio label="1">启用</Radio>
            <Radio label="2">禁用</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="菜单权限：">
          <!--          <template v-for="item in menuList">-->

          <!--          </template>-->
          <el-tree :data="treeData" :props="defaultProps">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <RadioGroup v-model="data.permissions" type="button" size="small" v-if="data.isEdit">
                  <Radio :label="data.p1">查看</Radio>
                  <Radio :label="data.p2">查看&编辑</Radio>
                  <Radio :label="data.p3">查看&删除</Radio>
                  <Radio :label="data.p4">全部</Radio>
                  <Radio label="">无权限</Radio>
                </RadioGroup>
              </span>
            </span>
          </el-tree>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button class="Button" type="primary" @click="create" :loading="loading5">确认新增</Button>
      </div>
    </Modal>

    <Modal v-model="modalDetail" title="详情" width="90">
      <div style="display:flex">
        <Form style="width:50%" ref="form" :model="detailData" :label-width="100">
          <FormItem label="单位名称：" prop="name">
            <p style="font-weight:bold">{{detailData.name}}</p>
          </FormItem>
          <FormItem label="单位地址：" prop="address">
            <p style="font-weight:bold">{{detailData.address}}</p>
          </FormItem>
          <FormItem label="手机号码：" prop="phone">
            <p style="font-weight:bold">{{detailData.phone}}</p>
          </FormItem>
          <FormItem label="场馆图片：" prop="pics">
            <img style="width:375px;height:175px" :src="'http://static.bowu66.com/'+detailData.pics"></img>
          </FormItem>
          <FormItem label="场馆简介：" prop="about">
            <p style="font-weight:bold;text-align:justify">{{detailData.about}}</p>
          </FormItem>
        </Form>
        <Form style="width:50%" ref="form" :model="detailData" :label-width="100">
          <!--           <FormItem label="微信昵称：" prop="username">
                      <p>{{detailData.username}}</p>
                    </FormItem>
                    <FormItem label="openId：" prop="username">
                      <p>{{detailData.username}}</p>
                    </FormItem> -->
          <FormItem label="创建时间：" prop="gmtCreate">
            <p style="font-weight:bold">{{detailData.gmtCreate}}</p>
          </FormItem>
          <FormItem label="入馆时段：" prop="bookRules">
            <template v-for="item in detailData.bookRules">
              <div style="display:flex">
                <p style="font-weight:bold;margin-right:10px">{{item.timeRange}}</p>
                <p style="font-weight:bold">{{item.num}}人</p>
              </div>
            </template>
          </FormItem>
          <FormItem label="闭馆日：" prop="closeWeeks">
            <p style="font-weight:bold">{{detailData.closeWeeks}}</p>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button class="Button" :disabled="detailData.states != 1" type="primary" @click="passAuth">通过</Button>
        <Button class="Button" :disabled="detailData.states != 1" type="error" @click="refuseAuth">拒绝</Button>
      </div>
    </Modal>

  </Card>
</template>

<script>
  import {md5} from '../config/md5.js'
  // 现在我要把obj字面量创建里的属性深拷贝（ 属性值是引用类型也要深拷贝 ）
  function deepClone(source){
    const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
    for(let keys in source){ // 遍历目标
      if(source.hasOwnProperty(keys)){
        if(source[keys] && typeof source[keys] === 'object'){ // 如果值是对象，就递归一下
          targetObj[keys] = source[keys].constructor === Array ? [] : {};
          targetObj[keys] = deepClone(source[keys]);
        }else{ // 如果不是，就直接赋值
          targetObj[keys] = source[keys];
        }
      }
    }
    return targetObj;
  }
  export default {
    inject: ['reload'],
    data () {
      return {
        modalDetail: false,
        detailData: {},
        detailDataID: '',
        yingc: false,
        loading1: false,
        loading2: false,
        loading3: false,
        loading4: false,
        loading5: false,
        updatatel: false,
        passwordModal: false,
        pswdText: '',
        tel: '',
        telId: '',
        delId: '',
        id: '',
        shuax: true,
        unlock: '',
        columns: [
          {title: '单位名称', key: 'museumName', align: 'center'},
          {title: '姓名', key: 'realName', align: 'center'},
          {title: '账号', key: 'nickName', align: 'center'},
          {title: '手机号码', key: 'phone', align: 'center'},
          // { title: "单位地址", key: "phone", align: "center" },
          {title: '创建时间', key: 'gmtCreate', align: 'center'},
          {
            title: '审核状态',
            align: 'center',
            key: 'states2',
            width:'180px',
            render: (h, params) => {
              let color = ''
              if (params.row.states2 == '待审核') {
                color = 'warning'
              }
              if (params.row.states2 == '审核通过') {
                color = 'primary'
              }
              if (params.row.states2 == '审核不通过') {
                color = 'error'
              }
              return h(
                'Tag',
                {
                  props: {type: 'dot', color: color}
                },
                params.row.states2
              )
            }
          },
          {
            title: '动态验证码',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h(
                  'i-switch',
                  {
                    props: {
                      value: params.row.validCodeSwitch
                    },
                    on: {
                      'on-change': () => {
                        this.changeSwitch(params)
                      }
                    }
                  }
                )])
            }
          },
          {
            title: '操作',
            align: 'center',
            width: 500,
            render: (h, params) => {
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'warning'
                    },
                    style: {
                      marginRight: '10px'
                    },
                    on: {
                      click: () => {
                        this.password(params)
                      }
                    }
                  },
                  '修改密码'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'warning'
                    },
                    style: {
                      marginRight: '10px'
                    },
                    on: {
                      click: () => {
                        this.onRowDblclick(params.row)
                      }
                    }
                  },
                  '查看'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'success',
                      disabled: params.row.states != 2
                    },
                    style: {
                      marginRight: '10px'
                    },
                    on: {
                      click: () => {
                        this.goDetail(params)
                      }
                    }
                  },
                  '前往场馆信息'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'info',
                      loading: this.loading3
                    },
                    on: {
                      click: () => {
                        this.jurisdiction(params)
                      }
                    }
                  },
                  '修改权限'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'warning'
                    },
                    style: {
                      marginTop: '10px'
                    },
                    on: {
                      click: () => {
                        this.updataTel(params)
                      }
                    }
                  },
                  '修改手机号'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'error'
                    },
                    style: {
                      marginTop: '10px',
                      marginLeft: '10px'
                    },
                    on: {
                      click: () => {
                        this.delete(params)
                      }
                    }
                  },
                  '删除'
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'warning'
                    },
                    style: {
                      marginTop: '10px',
                      marginLeft: '10px'
                    },
                    on: {
                      click: () => {
                        this.unlockAccount(params)
                      }
                    }
                  },
                  '解除30分钟登录锁定'
                )
              ])
            }
          }
        ],
        columns2: [
          {title: '单位名称', key: 'museumName', align: 'center'},
          {title: '手机号码', key: 'phone', align: 'center'},
          {title: '创建时间', key: 'gmtCreate', align: 'center'},
          {
            title: '操作',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'warning'
                    },
                    style: {
                      marginRight: '10px'
                    },
                    on: {
                      click: () => {
                        this.onRowDblclick(params.row)
                      }
                    }
                  },
                  '查看'
                )
              ])
            }
          }
        ],
        data: [],

        current: 1,
        size: 10,
        type: '0',
        states: '0',
        total: 0,
        phone: '',

        jurisdictionModal: false,
        menuList: [],
        menuId: '',

        addAccountModal: false,
        createData: {
          email: '',
          menus: [],
          museumId: '',
          password: '',
          phone: '',
          states: 0,
          username: ''
        },
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    // 开始请求接口
    created () {
      this.getMuseumDropdown()
    },
    // 方法列表
    methods: {
      addAccount () {
        this.createData = {
          email: '',
          museumId: '',
          password: '',
          phone: '',
          states: '1',
          username: '',
          realName:''
        }
        this.$http('/stage/menu/getMenuList', {}, 'get', (res) => {
          if (res.data.code === 200) {
            this.treeData = this.getMenusPermissions(res.data.data)
            this.addAccountModal = true
          } else {
            this.$Message.error(res.data.msg)
          }
        })
      },
      updataTel (params) {
        this.telId = params.row.id
        console.log(this.telId)
        this.updatatel = true
      },
      changeSwitch (params) {
        console.log(params)
        let validCodeSwitch = params.row.validCodeSwitch
        this.$http('/stage/user/closeAppUserValidCode', {
          id: params.row.id
        }, 'get', (res) => {
          console.log(res)
          if (res.data.code == 200 && res.data.data == true) {
            if (validCodeSwitch) {
              this.$Message.success('关闭动态验证码成功')
              this.getAppUserList()
            } else {
              this.$Message.success('开启动态验证码成功')
              this.getAppUserList()
            }
          } else {
            this.$Message.error(res.data.msg)
          }
        })
      },
      delete (params) {
        this.delId = params.row.id
        console.log(this.delId)
        this.open()
      },
      unlockAccount (params) {
        console.log(params)
        this.unlock = params.row.id
        console.log(params.row.id)
        this.unlockd()
      },
      unlockd () {
        this.$http(
          '/stage/user/unlockAccount',
          {
            id: this.unlock
          },
          'post',
          (res) => {
            console.log(res.data.data)
            if (res.data.data == true) {
              this.$message({
                type: 'success',
                message: '解除成功!'
              })
            } else if (res.data.data == false) {
              this.$message({
                type: 'warning',
                message: '解除失败,账户未锁定!'
              })
            }
          }
        )
      },
      open () {
        let that = this
        this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$http(
              '/stage/user/removeAccount',
              {
                id: this.delId
              },
              'post',
              (res) => {
                console.log(res)
                if (res.data.data == true) {
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  })
                  // this.reload();
                  this.getMuseumDropdown()
                }
              }
            )
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      updataTelSubmit () {
        console.log(1)
        let that = this
        this.$http(
          '/stage/user/alterAccountPhone',
          {
            id: this.telId,
            phone: this.tel
          },
          'post',
          (res) => {
            console.log(res.data.data)
            if (res.data.data == true) {
              that.open2()
              this.getMuseumDropdown()
              this.updatatel = false
            } else {
              that.open4()
            }
          }
        )
      },
      open2 () {
        this.$message({
          message: '修改成功！',
          type: 'success'
        })
      },
      open4 () {
        this.$message.error('err、错误！')
      },
      getMuseumDropdown () {
        this.loading1 = true
        this.$http('/stage/museum/getAppMuseumDropDown', {}, 'post', (res) => {
          if (res.data.code == 200) {
            this.museumList = res.data.data
            // this.museumList.unshift({name:'超级管理员',id:'0'})
            this.getAppUserList()
          } else {
            this.$Message.error(res.data.msg)
          }
        })
      },
      getMenusPermissions (mp, oldPer = null) {
        let arr = []
        for (let i = 0; i < mp.length; i++) {
          let isEdit = false;
          let permissions = '';
          let {menuName: label, id, parentId, stringPermissions: p} = mp[i]
          if (p.length > 1) isEdit = true;
          let quan = {
            p1: `${p[0]}`,
            p2: `${p[0]},${p[1]}`,
            p3: `${p[0]},${p[2]}`,
            p4: `${p[0]},${p[1]},${p[2]}`
          }
          if(oldPer && oldPer.length) {
            for (let i = 0; i < oldPer.length; i++) {
              if(oldPer[i].id === id) {
                permissions = oldPer[i]['stringPermissions'].join(",");
                oldPer.splice(i, 1);
                i--;
              }
            }
          }
          arr[i] = {label, id, isEdit, parentId, permissions, ...quan}
          if (mp[i].children && mp[i].children.length) {
            arr[i].children = this.getMenusPermissions(mp[i].children, oldPer)
          }
        }
        return arr
      },
      create () {
        this.loading5 = true;
        let arr = this.simple(this.treeData);
        this.$http(
          '/stage/menu/createAccount',
          {
            email: this.createData.email,
            menus: arr,
            museumId: this.createData.museumId,
            password: md5(this.createData.password),
            phone: this.createData.phone,
            states: parseInt(this.createData.states),
            username: this.createData.username,
            realName:this.createData.realName
          },
          'post',
          (res) => {
            if (res.data.code == 200) {
              this.$Message.success('新增账号成功')
              this.addAccountModal = false
              this.getAppUserList()
            } else {
              this.$Message.error(res.data.msg)
            }
            this.loading5 = false
          }
        )
      },
      simple(mp) {
        let arr = []
        for (let i = 0; i < mp.length; i++) {
          let { id, parentId, permissions } = mp[i]
          arr[i] = { id, parentId, permissions }
          if (mp[i].children && mp[i].children.length) {
            arr[i].children = this.simple(mp[i].children)
          }
        }
        return arr
      },
      jurisdiction (params) {
        let { permissions, id } = deepClone(params.row);
        this.loading3 = true
        this.menuId = id
        this.params = params;
        console.log(permissions)
        this.$http('/stage/menu/getMenuList', {}, 'get', (res) => {
          if (res.data.code == 200) {
            this.treeData = this.getMenusPermissions(res.data.data, permissions);
            console.log(this.treeData)
            debugger
            this.jurisdictionModal = true
          } else {
            this.$Message.error(res.data.msg)
          }
          this.loading3 = false
        })
      },
      submit2 () {
        this.loading4 = true;
        console.log(this.treeData)
        let arr = this.simple(this.treeData);
        arr = this.flatten(arr).filter(item => item.permissions);
        console.log(arr);
        this.$http(
          '/stage/menu/updatePermission',
          {
            id: this.menuId,
            menus: arr
          },
          'post',
          (res) => {
            if (res.data.code == 200) {
              this.$Message.success('修改权限成功')
              this.getAppUserList()
              this.jurisdictionModal = false
            } else {
              this.$Message.error(res.data.msg)
            }
            this.loading4 = false
          }
        )
      },
      flatten(arr) {
        let renchong = deepClone(arr)
        for (let item of renchong) {
          if(item.children && item.children.length) {
            renchong = renchong.concat(this.flatten(item.children))
            delete item.children
          }
        }
        return renchong;
      },
      getAppUserList () {
        this.loading1 = true
        this.$http(
          '/stage/user/getAppUserList',
          {
            current: this.current,
            size: this.size,
            states: this.states == '0' ? '' : this.states,
            // type: this.type == '0' ? '' : this.type,
            phone: this.phone,
            type: 2
          },
          'post',
          (res) => {
            if (res.data.code == 200) {
              this.data = res.data.data.records
              for (let i = 0; i < this.data.length; i++) {
                if (this.data[i].states == 1) {
                  this.data[i].states2 = '待审核'
                }
                if (this.data[i].states == 2) {
                  this.data[i].states2 = '审核通过'
                }
                if (this.data[i].states == 3) {
                  this.data[i].states2 = '审核不通过'
                }
                if (this.data[i].type == 1) {
                  this.data[i].type2 = '普通用户'
                }
                if (this.data[i].type == 2) {
                  this.data[i].type2 = '博物馆人员'
                }
                if (this.data[i].type == 3) {
                  this.data[i].type2 = '播音员'
                }
              }
              this.total = res.data.data.total
            } else {
              this.$Message.error(res.data.msg)
            }
            this.loading1 = false
          }
        )
      },
      changePage (e) {
        this.current = e
        this.getAppUserList()
      },
      change () {
        this.current = 1
        this.getAppUserList()
      },

      password (params) {
        this.passwordModal = true
        this.pswdText = ''
        this.id = params.row.id
      },
      submit () {
        if (this.pswdText == '') {
          this.$Message.error('请输入新密码')
          return false
        }
        this.loading2 = true
        this.$http(
          '/stage/user/updatePassword',
          {
            id: this.id,
            password: md5(this.pswdText)
          },
          'post',
          (res) => {
            if (res.data.code == 200) {
              this.$Message.success('修改密码成功')
            } else {
              this.$Message.error(res.data.msg)
            }
            this.loading2 = false
          }
        )
      },

      // 双击查看提交内容
      onRowDblclick (data) {
        this.modalDetail = true
        this.$http(
          '/stage/museum/getMuseumSubmitMsg',
          {
            museumId: data.museumId
          },
          'get',
          (res) => {
            if (res.data.code == 200) {
              this.detailDataID = data.id
              this.detailData = res.data.data
              this.detailData.states = data.states
            } else {
              this.$Message.error(res.data.msg)
            }
          }
        )
      },
      // 同意审核
      passAuth (params) {
        this.$Modal.confirm({
          title: '提示',
          content: '<p>确定要同意此账号吗？</p>',
          onOk: () => {
            this.loading1 = true
            this.$http(
              '/stage/user/authAppUser',
              {
                id: this.detailDataID,
                states: 2
              },
              'post',
              (res) => {
                if (res.data.code == 200) {
                  this.$Message.success('审核同意成功')
                  this.current = 1
                  this.getAppUserList()
                  this.modalDetail = false
                } else {
                  this.$Message.error(res.data.msg)
                }
                this.loading1 = false
              }
            )
          },
          onCancel: () => {
          }
        })
      },
      // 拒绝审核
      refuseAuth (params) {
        this.$Modal.confirm({
          title: '提示',
          content: '<p>确定要拒绝此账号吗？</p>',
          onOk: () => {
            this.loading1 = true
            this.$http(
              '/stage/user/authAppUser',
              {
                id: this.detailDataID,
                states: 3
              },
              'post',
              (res) => {
                if (res.data.code == 200) {
                  this.$Message.success('审核拒绝成功')
                  this.current = 1
                  this.getAppUserList()
                  this.modalDetail = false
                } else {
                  this.$Message.error(res.data.msg)
                }
                this.loading1 = false
              }
            )
          },
          onCancel: () => {
          }
        })
      },
      // 前往详情
      goDetail (data) {
        this.$router.push({
          name: '场馆信息',
          params: {
            id: data.row.museumId
          }
        })
      }
    }
  }
</script>

<style scoped>
  >>>.el-tree-node {
    margin-bottom: 10px;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
